package org.calzz.jajb.converter;

import java.math.BigDecimal;
import java.math.BigInteger;

import org.calzz.jajb.JsonDeserializer;
import org.calzz.jajb.JsonSerializer;
import org.calzz.jajb.io.IWriter;
import org.springframework.core.MethodParameter;

/**
 * The default converter for numeric types - also for the primitive ones.
 * 
 * @author Marek Brodziak <marek.brodziak@gmail.com>
 * @author Piotr Pejas <piotr.pejas@gmail.com>
 * @since Feb 6, 2008
 */
public class NumberConverter implements IConverter {

	/*
	 * (non-Javadoc)
	 * @see org.jamjam.jajb.converter.IConverter#canConvert(java.lang.Class)
	 */
	public boolean canConvert(Class<?> clazz) {
		return false || Short.class.equals(clazz) || short.class.equals(clazz) || Integer.class.equals(clazz) || int.class.equals(clazz) || Long.class.equals(clazz) || long.class.equals(clazz) || BigInteger.class.equals(clazz) || Float.class.equals(clazz) || float.class.equals(clazz) || Double.class.equals(clazz) || double.class.equals(clazz) || BigDecimal.class.equals(clazz);
	}

	/*
	 * (non-Javadoc)
	 * @see org.jamjam.jajb.converter.IConverter#marshal(java.lang.Object,
	 *      java.lang.String, org.jamjam.jajb.io.IWriter,
	 *      org.jamjam.jajb.JsonSerializer)
	 */
	public void marshal(Object obj, String name, IWriter writer, JsonSerializer serializer) {
		writer.writeKey(name);
		writer.writeValue(obj.toString());
	}

	/*
	 * (non-Javadoc)
	 * @see org.jamjam.jajb.converter.IConverter#unmarshal(java.lang.Object,
	 *      java.lang.Class, org.jamjam.jajb.JsonDeserializer)
	 */
	public <T> Object unmarshal(Object env, Class<T> clazz, JsonDeserializer deserializer, MethodParameter methodParam) {
		if (Short.class.equals(clazz) || short.class.equals(clazz)) {
			return Short.parseShort(env.toString());
		}
		if (Integer.class.equals(clazz) || int.class.equals(clazz)) {
			return Integer.parseInt(env.toString());
		}
		if (Long.class.equals(clazz) || long.class.equals(clazz)) {
			return Long.parseLong(env.toString());
		}
		if (BigInteger.class.equals(clazz)) {
			return new BigInteger(env.toString());
		}
		if (Float.class.equals(clazz) || float.class.equals(clazz)) {
			return Float.parseFloat(env.toString());
		}
		if (Double.class.equals(clazz) || double.class.equals(clazz)) {
			return Double.parseDouble(env.toString());
		}
		if (BigDecimal.class.equals(clazz)) {
			return new BigDecimal(env.toString());
		}

		return null;
	}
}
